package org.csu.mypetstore.web.servlets;

import com.google.gson.Gson;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;
import org.csu.mypetstore.service.SearchService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//该类用于响应用户对于网站内容的浏览、搜索
public class BrowseProductServlet extends BaseServlet{
    //主界面
    public static final String MAIN = "/WEB-INF/jsp/catalog/Main.jsp";

    //category界面
    public static final String VIEW_CATEGORY = "/WEB-INF/jsp/catalog/Category.jsp";

    //product界面
    public static final String VIEW_PRODUCT = "/WEB-INF/jsp/catalog/Product.jsp";

    //item界面
    public static final String VIEW_ITEM = "/WEB-INF/jsp/catalog/Item.jsp";

    //搜索结果界面
    public static final String VIEW_SEARCH_PRODUCTS = "/WEB-INF/jsp/catalog/SearchProducts.jsp";

    //帮助界面
    public static final String HELP = "/WEB-INF/jsp/common/Help.jsp";

    //浏览主界面
    protected void viewMain(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(MAIN).forward(req,resp);
    }

    //浏览category
    protected void viewCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String categoryId = req.getParameter("categoryId");
        CatalogService service = new CatalogService();
        Category category = service.getCategory(categoryId);
        List<Product> productList = service.getProductListByCategory(categoryId);
        HttpSession session = req.getSession();
        session.setAttribute("category",category);
        session.setAttribute("productList",productList);

        req.getRequestDispatcher(VIEW_CATEGORY).forward(req,resp);
    }

    //在浮窗上浏览category
    protected void ajaxViewCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CatalogService service = new CatalogService();
        List<Product> birdsProductList = service.getProductListByCategory("Birds");
        List<Product> catsProductList = service.getProductListByCategory("Cats");
        List<Product> fishProductList = service.getProductListByCategory("Fish");
        List<Product> dogsProductList = service.getProductListByCategory("Dogs");
        List<Product> reptilesProductList = service.getProductListByCategory("Reptiles");

        //封装成Map对象
        Map<String,Object> allCategories = new HashMap<>();
        allCategories.put("Birds",birdsProductList);
        allCategories.put("Cats",catsProductList);
        allCategories.put("Fish",fishProductList);
        allCategories.put("Dogs",dogsProductList);
        allCategories.put("Reptiles",reptilesProductList);

        HttpSession session = req.getSession();
        session.setAttribute("allCategories",allCategories);
    }

    //浏览product
    protected void viewProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //需要的一些变量
        String productId;

        productId = req.getParameter("productId");
        CatalogService service = new CatalogService();
        Product product = service.getProduct(productId);

        List<Item> itemList = service.getItemListByProduct(productId);

        HttpSession session = req.getSession();
        session.setAttribute("product",product);
        session.setAttribute("itemList",itemList);

        req.getRequestDispatcher(VIEW_PRODUCT).forward(req,resp);
    }

    //浏览item
    protected void viewItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //需要的一些变量
        String itemId;
        LogService logService;

        itemId = req.getParameter("itemId");
        CatalogService service = new CatalogService();

        Item item = service.getItem(itemId);
        Product product = service.getProduct(item.getProductId());

        HttpSession session = req.getSession();
        session.setAttribute("item",item);
        session.setAttribute("product",product);

        Account account = (Account) session.getAttribute("account");
        //如果用户已经登录
        if(account != null){
            //创建一个ViewItemLog
            ViewItemLog viewItemLog = new ViewItemLog();
            viewItemLog.setUsername(account.getUsername());
            viewItemLog.setItemId(itemId);
            viewItemLog.setDescn(item.getAttr1() + " " + product.getName());
            viewItemLog.setListPrice(item.getListPrice());
            viewItemLog.setDate(new Date());
            viewItemLog.setCount(1);

            //准备工作
            logService = new LogService();
            UserLog userLog = logService.getUserLog(account.getUsername());
            //如果说已经有这条浏览记录了，更新记录
            if(userLog.containsViewLog(viewItemLog)){
                logService.updateViewLog(account.getUsername(),viewItemLog.getItemId());
            }
            //没有
            else{
                logService.insertViewLog(viewItemLog);
            }
        }
        req.getRequestDispatcher(VIEW_ITEM).forward(req,resp);
    }

    //浏览搜索结果
    protected void viewSearchProducts(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //需要的一些变量
        String keyword;

        keyword = req.getParameter("keyword");

        CatalogService service = new CatalogService();
        List<Product> productList = service.searchProductList(keyword);

        HttpSession session = req.getSession();
        session.setAttribute("productList",productList);

        req.getRequestDispatcher(VIEW_SEARCH_PRODUCTS).forward(req,resp);
    }

    //浏览帮助界面
    protected void viewHelp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getRequestDispatcher(HELP).forward(req,resp);
    }

    //自动补全
    protected void autoComplete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //获取搜索框输入的内容
        String keyword=req.getParameter("keyword");
        keyword=new String(keyword.getBytes("iso-8859-1"), "utf-8");
        //向server层调用相应的业务
        SearchService searchService=new SearchService();
        String res=searchService.getItemListByProduct_2(keyword);
        //返回结果
        resp.getWriter().write(res);
    }

    //自动补全相关
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SearchService service = new SearchService();
        resp.setContentType("text/plain;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String productName=req.getParameter("productName");
        String productId=service.getProductId(productName);
        resp.getWriter().write(productId);
    }
}
